<template>
  <div class="emt">
    <el-row gutter="10">
      <el-col :span="6">
        <el-card class="sur-card">
          <div class="sur-card-title" slot="header">
            <span
              >正在为规格名[<span style="color: red;">{{ skuName }}</span
              >]编辑模板</span
            >
          </div>
          <el-form label-position="left" label-width="100px">
            <el-form-item label="模板名称">
              <el-input size="small" v-model="sampleModel.title"></el-input>
            </el-form-item>
            <el-form-item label="模板编码">
              <el-input
                size="small"
                v-model="sampleModel.sampleCode"
              ></el-input>
            </el-form-item>
            <el-form-item label="提示客户信息">
              <el-input size="small" v-model="sampleModel.tips"></el-input>
            </el-form-item>
            <el-form-item label="风格分类">
              <el-select size="small" v-model="sampleModel.styleId">
                <el-option
                  v-for="style in styleList"
                  :key="style.id"
                  :label="style.name"
                  :value="style.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="打印面数量">
              <el-select
                size="small"
                disabled
                placeholder="暂时只支持正面打印"
              ></el-select>
            </el-form-item>
            <el-form-item label="效果图">
              <el-image
                v-if="sampleModel.effectImg"
                :src="sampleModel.effectImg"
                :preview-src-list="Array.of(sampleModel.effectImg)"
                fit="contain"
                style="height: 100px;width: 100px;"
              ></el-image>
              <span v-else style="font-size: 14px;"
                >保存右侧画布即可生成效果图</span
              >
            </el-form-item>
            <el-form-item label="排序">
              <el-input-number
                size="small"
                :min="1"
                v-model="sampleModel.sort"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="画布数据">
              <el-input
                type="textarea"
                size="small"
                :rows="4"
                readonly
                v-model="sampleModel.frontCanvasDataJson"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button size="small" type="danger" @click="onSaveSampleModel"
                >保存当前模板</el-button
              >
              <div>保存前，请先保存右侧画布内容</div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card class="sur-card">
          <div class="sur-card-title" slot="header">
            <span>模板编辑</span>
          </div>
          <el-row>
            <div
              style="display: flex;padding-bottom: 8px;border-bottom: 1px solid #dcdfe6;"
            >
              <div>
                <!-- <span style=" font-size: 14px;color: #303133;margin: 0 5px;"
                                  >实体图:</span
                                >-->
                <el-upload
                  style="display: inline-block;"
                  :http-request="handleEntityImgUpload"
                  :show-file-list="false"
                >
                  <el-button
                    size="small"
                    plain
                    type="primary"
                    icon="el-icon-picture"
                    >第一步选择实体图</el-button
                  >
                </el-upload>
              </div>
              <div>
                <!--<span style=" font-size: 14px;color: #303133;margin: 0 5px;"
                                  >刀模图:</span
                                >-->
                <el-upload
                  style="display: inline-block;margin-left: 8px;"
                  :http-request="handleOverlayImgUpload"
                  :show-file-list="false"
                >
                  <el-button
                    size="small"
                    plain
                    type="primary"
                    icon="el-icon-picture"
                    >第二步选择刀模图</el-button
                  >
                </el-upload>
              </div>
              <div>
                <!-- <span style=" font-size: 14px;color: #303133;margin:0 5px;"
                                  >添加贴纸:</span
                                >-->
                <el-upload
                  style="display: inline-block;margin-left: 8px;"
                  :http-request="handlePasterImgUpload"
                  :show-file-list="false"
                >
                  <el-button
                    size="small"
                    plain
                    type="primary"
                    icon="el-icon-picture"
                    >第三步添加贴纸</el-button
                  >
                </el-upload>
              </div>
              <el-button
                size="small"
                type="danger"
                style="margin-left: auto;"
                @click="onSaveCanvas"
                >保存画布</el-button
              >
            </div>
          </el-row>
          <div class="canvas-area" style="display: flex;">
            <canvas style="width: 620px;" id="canvasFront"></canvas>
            <div
              style="margin-left: 20px;border-left: 1px solid #dcdfe6; padding-left: 18px;width: 100%;"
            >
              <el-form label-position="left" label-width="100px">
                <!--                <el-divider>文字属性</el-divider>-->
                <div>
                  <el-form-item label="文字内容：">
                    <el-input
                      type="textarea"
                      v-model="textProps.textValue"
                      size="small"
                      placeholder="请输入文字内容"
                    >
                    </el-input>
                  </el-form-item>
                  <el-form-item label="字体样式：">
                    <el-select
                      size="small"
                      v-model="textProps.fontFamily"
                      placeholder="请选择字体样式"
                    >
                      <el-option value="千图小兔体"
                        ><span
                          style="font-family: '千图小兔体';font-size: 18px;font-weight: bolder"
                          >千图小兔体</span
                        ></el-option
                      >
                      <el-option value="上首锐圆极细体"
                        ><span
                          style="font-family: '上首锐圆极细体';font-size: 18px;font-weight: bolder;"
                          >上首锐圆极细体</span
                        ></el-option
                      >
                      <el-option value="锐字云字库行草体"
                        ><span
                          style="font-family: '锐字云字库行草体';font-size: 18px;font-weight: bolder"
                          >锐字云字库行草体</span
                        ></el-option
                      >
                      <el-option value="青柠幼圆体"
                        ><span
                          style="font-family: '青柠幼圆体';font-size: 18px;font-weight: bolder"
                          >青柠幼圆体</span
                        ></el-option
                      >
                      <el-option value="于洪亮毛笔隶书简体"
                        ><span
                          style="font-family: '于洪亮毛笔隶书简体';font-size: 18px;font-weight: bolder"
                          >于洪亮毛笔隶书简体</span
                        ></el-option
                      >
                      <el-option value="法棍体"
                        ><span
                          style="font-family: '法棍体';font-size: 18px;font-weight: bolder"
                          >法棍体</span
                        ></el-option
                      >
                      <el-option value="Modak"
                        ><span
                          style="font-family: 'Modak';font-size: 18px;font-weight: bolder"
                          >Modak</span
                        ></el-option
                      >
                      <el-option value="彤彤体"
                        ><span
                          style="font-family: '彤彤体';font-size: 18px;font-weight: bolder"
                          >彤彤体</span
                        ></el-option
                      >
                    </el-select>
                  </el-form-item>
                  <el-form-item label="文字颜色：">
                    <el-color-picker
                      v-model="textProps.textColor"
                      show-alpha
                    ></el-color-picker>
                  </el-form-item>
                  <el-form-item label="文字大小：">
                    <el-slider
                      v-model="textProps.fontSize"
                      :min="8"
                      :max="60"
                      :step="1"
                    ></el-slider>
                  </el-form-item>
                  <el-form-item label="文字粗细：">
                    <el-slider
                      v-model="textProps.fontWeight"
                      :min="100"
                      :max="900"
                      :step="100"
                    ></el-slider>
                  </el-form-item>
                  <el-form-item label="文字阴影：">
                    <el-input
                      v-model="textProps.shadow"
                      size="small"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="画笔颜色：">
                    <el-color-picker
                      v-model="textProps.stroke"
                      show-alpha
                    ></el-color-picker>
                  </el-form-item>
                  <el-form-item label="画笔宽度：">
                    <el-slider
                      v-model="textProps.strokeWidth"
                      :min="0"
                      :max="8"
                      :step="1"
                    ></el-slider>
                  </el-form-item>
                  <el-form-item label="文字背景色：">
                    <el-color-picker
                      v-model="textProps.textBackgroundColor"
                      show-alpha
                    ></el-color-picker>
                  </el-form-item>
                  <el-form-item label="对齐方式：">
                    <el-select size="small" v-model="textProps.textAlign">
                      <el-option label="居中" value="center"></el-option>
                      <el-option label="左对齐" value="left"></el-option>
                      <el-option label="右对齐" value="right"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="行高：">
                    <el-input-number
                      size="small"
                      v-model="textProps.lineHeight"
                      :min="1"
                      :max="5"
                    ></el-input-number>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      type="primary"
                      size="small"
                      @click="onSaveText"
                      >{{
                        textProps.isNew ? "添加文字" : "更新文字"
                      }}</el-button
                    >
                  </el-form-item>
                </div>
              </el-form>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- <el-button @click="onSaveJSON">保存</el-button>
        <el-button @click="onSaveEffect">效果图</el-button>-->
  </div>
</template>

<script>
import { fabric } from "fabric-with-gestures";
import {
  getUploadItemMediaToken,
  uploadFileToAliOss
} from "@/api/admin-api/FileApi";
import { generateUUID } from "@/utils/commonUtil";
const deleteIcon =
  "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg version='1.1' id='Ebene_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='595.275px' height='595.275px' viewBox='200 215 230 470' xml:space='preserve'%3E%3Ccircle style='fill:%23F44336;' cx='299.76' cy='439.067' r='218.516'/%3E%3Cg%3E%3Crect x='267.162' y='307.978' transform='matrix(0.7071 -0.7071 0.7071 0.7071 -222.6202 340.6915)' style='fill:white;' width='65.545' height='262.18'/%3E%3Crect x='266.988' y='308.153' transform='matrix(0.7071 0.7071 -0.7071 0.7071 398.3889 -83.3116)' style='fill:white;' width='65.544' height='262.179'/%3E%3C/g%3E%3C/svg%3E";
const img = document.createElement("img");
img.src = deleteIcon;

function renderDeleteIcon(ctx, left, top, styleOverride, fabricObject) {
  const size = this.cornerSize;
  ctx.save();
  ctx.translate(left, top);
  ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle));
  ctx.drawImage(img, -size / 2, -size / 2, size, size);
  ctx.restore();
}
fabric.Object.prototype.transparentCorners = false;
fabric.Object.prototype.cornerColor = "blue";
/**
 * Item name is unique
 */
fabric.Canvas.prototype.getObjectByName = function(name) {
  var object = null,
    objects = this.getObjects();

  for (var i = 0, len = this.size(); i < len; i++) {
    if (objects[i].name && objects[i].name === name) {
      object = objects[i];
      break;
    }
  }

  return object;
};
import initAligningGuidelines from "@/plugins/aligning_guidelines.js";
import initCenteringGuidelines from "@/plugins/centering_guidelines";
import { getSampleStyleByPage } from "@/api/admin-api/SampleStyleApi";
import {
  getTabletMuffTemplateById,
  saveTabletMuffTemp,
  updateTabletMuffTemp
} from "@/api/admin-api/DiyTabletMuffApi";
const overlayImg = require("@/assets/images/air_overlay.png");
const bottomImg = require("@/assets/images/airpos_pro_2_bottom.png");
const cutImg = require("@/assets/images/ear_tiezhi.png");
const entityImg = require("@/assets/images/entity_aripods.png");
const canvasJSONData =
  '{"version":"4.2.0","objects":[{"type":"rect","version":"4.2.0","originX":"left","originY":"top","left":90.71,"top":45,"width":418.58,"height":510,"fill":"#ffffff","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"rx":0,"ry":0,"centeredRotation":true,"selectable":false},{"type":"image","version":"4.2.0","originX":"left","originY":"top","left":90.71,"top":45,"width":435,"height":530,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":0.96,"scaleY":0.96,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"cropX":0,"cropY":0,"centeredRotation":true,"selectable":false,"src":"http://localhost:9019/dist/img/airpos_pro_2_bottom.7e12dd31.png","crossOrigin":"anonymous","filters":[]},{"type":"image","version":"4.2.0","originX":"center","originY":"center","left":200,"top":200,"width":149,"height":146,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"cropX":0,"cropY":0,"centeredRotation":true,"selectable":true,"src":"http://localhost:9019/dist/img/ear_tiezhi.fe7ae4be.png","crossOrigin":"anonymous","filters":[]}],"background":"#c8ccd4a3","overlayImage":{"type":"image","version":"4.2.0","originX":"left","originY":"top","left":90.71,"top":45,"width":435,"height":530,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeMiterLimit":4,"scaleX":0.96,"scaleY":0.96,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"cropX":0,"cropY":0,"centeredRotation":true,"selectable":true,"src":"http://localhost:9019/dist/img/airpos_pro_2_overlay.c6998ea8.png","crossOrigin":"anonymous","filters":[]},"centeredRotation":false}';
export default {
  name: "TabletMuffTemplateEdit",
  props: {
    skuName: [],
    skuId: [],
    tempId: [] //已存在的模板ID
  },
  data() {
    return {
      styleList: [], //风格列表
      sampleModel: {
        styleId: undefined,
        skuId: undefined,
        skuName: undefined,
        title: undefined,
        sampleCode: undefined,
        effectImg: undefined,
        tips: undefined,
        editable: true,
        sort: 1,
        frontCanvasDataJson: undefined
      },
      canvasProps: {
        canvasObj: null, //fabric 对象
        entityImage: null, // 实体图
        overlayImage: null // 刀模图
      },
      textProps: {
        textValue: "",
        fontSize: 30,
        fontFamily: "",
        textColor: "#000000", //文字颜色
        fontWeight: 400,
        shadow: "", //文字阴影
        stroke: "", //画笔颜色
        strokeWidth: 0, // 画笔宽度
        textAlign: "center", //文字对齐方式,多行
        lineHeight: 1, //行高,
        textBackgroundColor: "", //文字背景色
        isNew: true,
        textBox: null //当 isNew为false时存在
      },
      text: ""
    };
  },
  watch: {
    textProps: {
      handler(n, o) {
        // console.log("n", n);
        // console.log("o", o);
        // console.log("textProps", this.textProps);
        // this.onUpdateText();
      },
      deep: true
    }
  },
  methods: {
    onSaveSampleModel() {
      console.log("准备提交模型数据", this.sampleModel);
      if (!this.sampleModel.title) {
        this.$message.error("请输入模板名称");
        return;
      }
      if (!this.sampleModel.frontCanvasDataJson) {
        this.$message.error("请先保存右侧的画布");
        return;
      }
      this.$loading();
      if (this.sampleModel.id) {
        //更新
        updateTabletMuffTemp(this.sampleModel)
          .then(() => {
            this.$loading().close();
            this.$message.success("保存成功");
            setTimeout(() => {
              window.location.reload();
            }, 500);
          })
          .catch(() => {
            this.$loading().close();
          });
      } else {
        // 保存
        saveTabletMuffTemp(this.sampleModel)
          .then(() => {
            this.$loading().close();
            this.$message.success("保存成功");
          })
          .catch(() => {
            this.$loading().close();
          });
      }
    },
    async onSaveCanvas() {
      console.log("this.canvasProps", this.canvasProps);
      if (!this.canvasProps.entityImage || !this.canvasProps.overlayImage) {
        this.$message.error("请先完成画布创作");
        return;
      }
      //生产效果图
      const effectImgUrl = await this.saveEffectImg();
      console.log("effectImgUrl", effectImgUrl);
      //保存canvas数据
      console.log(
        "canvasData",
        JSON.stringify(
          this.canvasProps.canvasObj.toJSON([
            "centeredRotation",
            "selectable",
            "name",
            "clipPath"
          ])
        )
      );
      this.sampleModel.effectImg = effectImgUrl;
      this.sampleModel.frontCanvasDataJson = JSON.stringify(
        this.canvasProps.canvasObj.toJSON([
          "centeredRotation",
          "selectable",
          "name",
          "clipPath"
        ])
      );
    },
    //上传实体图，第一步
    async handleEntityImgUpload({ file }) {
      if (this.canvasProps.entityImage) {
        this.canvasProps.canvasObj.remove(this.canvasProps.entityImage);
        this.canvasProps.entityImage = null;
      }
      const imgUrl = await this.uploadToOss(file);
      const entityImage = await this.loadFabricImageAsync(imgUrl);
      entityImage.scaleToWidth(600 * 0.9);
      entityImage.selectable = false;
      entityImage.name = "entityImage";
      this.canvasProps.canvasObj.add(entityImage);
      this.canvasProps.canvasObj.centerObject(entityImage);
      this.canvasProps.entityImage = entityImage;
      //添加裁切区域
      const clipPath = new fabric.Rect({
        left: entityImage.left,
        top: entityImage.top,
        width: entityImage.getScaledWidth(),
        height: entityImage.getScaledHeight()
      });
      this.canvasProps.canvasObj.clipPath = clipPath;
      this.canvasProps.canvasObj.renderAll();
    },
    //第二步，上传刀模图
    async handleOverlayImgUpload({ file }) {
      if (this.canvasProps.overlayImage) {
        this.canvasProps.canvasObj.remove(this.canvasProps.overlayImage);
        this.canvasProps.overlayImage = null;
      }
      const imgUrl = await this.uploadToOss(file);
      const overlayImage = await this.loadFabricImageAsync(imgUrl);
      this.canvasProps.canvasObj.setOverlayImage(
        overlayImage,
        this.canvasProps.canvasObj.renderAll.bind(this.canvasProps.canvasObj),
        {
          name: "overlayImage",
          left: this.canvasProps.entityImage.left,
          top: this.canvasProps.entityImage.top,
          scaleX: this.canvasProps.entityImage.scaleX,
          scaleY: this.canvasProps.entityImage.scaleY
        }
      );
      this.canvasProps.overlayImage = overlayImage;
    },
    //第三步，上传贴纸
    async handlePasterImgUpload({ file }) {
      const imgUrl = await this.uploadToOss(file);
      const tiezhi = await this.loadFabricImageAsync(imgUrl);
      tiezhi.set({
        left: 0,
        top: 0,
        originX: "center",
        originY: "center",
        centeredScaling: true,
        centeredRotation: true
      });
      tiezhi.scaleToHeight(100);
      this.canvasProps.canvasObj.centerObject(tiezhi);
      this.canvasProps.canvasObj.add(tiezhi);
      this.canvasProps.canvasObj.setActiveObject(tiezhi);
    },
    //更新文字
    onUpdateText() {
      if (!this.textProps.textBox) {
        return;
      }
      this.textProps.textBox.set({
        fontSize: this.textProps.fontSize,
        fontWeight: this.textProps.fontWeight,
        fill: this.textProps.textColor,
        text: this.textProps.textValue,
        fontFamily: this.textProps.fontFamily,
        shadow: this.textProps.shadow,
        stroke: this.textProps.stroke,
        strokeWidth: this.textProps.strokeWidth,
        textAlign: this.textProps.textAlign,
        lineHeight: this.textProps.lineHeight,
        textBackgroundColor: this.textProps.textBackgroundColor
      });
      this.canvasProps.canvasObj.renderAll();
    },
    //第四步添加新文字
    onSaveText() {
      if (!this.textProps.textValue) {
        if (!this.textProps.isNew) {
          this.canvasProps.canvasObj.remove(this.textProps.textBox);
          this.textProps = this.$options.data().textProps;
        } else {
          this.$message.error("请输入文字");
          return;
        }
      }
      if (!this.textProps.isNew) {
        this.onUpdateText();
        return;
      }
      const textBox = new fabric.Text(this.textProps.textValue, {
        left: 0,
        top: 0,
        hasControls: true,
        hasBorders: true,
        borderColor: "#000000",
        fill: this.textProps.textColor, //文字颜色
        fontSize: this.textProps.fontSize,
        fontWeight: this.textProps.fontWeight,
        fontFamily: this.textProps.fontFamily,
        shadow: this.textProps.shadow,
        stroke: this.textProps.stroke,
        strokeWidth: this.textProps.strokeWidth,
        textAlign: this.textProps.textAlign,
        lineHeight: this.textProps.lineHeight,
        textBackgroundColor: this.textProps.textBackgroundColor,
        // shadow: "rgba(0,0,0,0.3) 5px 5px 5px",
        // fontStyle: "italic",
        // stroke: "#c3bfbf", //画笔边框样式
        // strokeWidth: 3, //画笔 边框
        // textBackgroundColor: "rgb(0,200,0)", //文字背景色
        // angle: 90,
        // lineHeight: 3, //行高
        // textAlign: "right", //文字对齐，多行文本有用
        // perPixelTargetFind: true,
        snapAngle: 45,
        editable: true,
        snapThreshold: 5,
        originX: "center",
        originY: "center",
        editingBorderColor: "#ff8d23"
      });
      this.textProps.textBox = textBox;
      this.textProps.isNew = false;
      this.canvasProps.canvasObj.centerObject(textBox);
      this.canvasProps.canvasObj.add(textBox);
      this.canvasProps.canvasObj.setActiveObject(textBox);
      // this.textProps = this.$options.data().textProps;
    },
    //上传图片到阿里云
    uploadToOss(file) {
      return new Promise(resolve => {
        // 上传至阿里云oss
        this.$loading();
        getUploadItemMediaToken().then(uploadToken => {
          // 上传文件
          const formData = new FormData();
          const fileKey = uploadToken.dir.concat(file.name);
          formData.append("key", fileKey);
          formData.append("policy", uploadToken.policy);
          formData.append("OSSAccessKeyId", uploadToken.ossAccessKeyId);
          formData.append("success_action_status", "200");
          formData.append("signature", uploadToken.signature);
          formData.append("file", file);
          uploadFileToAliOss(uploadToken.fileHost, formData).then(() => {
            resolve("https://asset.fanghaowu.com/" + fileKey);
            this.$loading().close();
          });
        });
      });
    },

    async saveEffectImg() {
      return new Promise(resolve => {
        const effectImgData = this.canvasProps.canvasObj.toDataURL({
          format: "png",
          multiplier: 1,
          quality: 1,
          left: this.canvasProps.entityImage.left,
          top: this.canvasProps.entityImage.top,
          width: this.canvasProps.entityImage.getScaledWidth(),
          height: this.canvasProps.entityImage.getScaledHeight()
        });
        console.log("jjjj");
        let file = this.dataURLtoFile(effectImgData, generateUUID() + ".png");
        this.uploadToOss(file).then(filePath => {
          resolve(filePath);
        });
      });

      // this.canvasProps.entityImage.visible = false;
      // this.canvasProps.overlayImage.globalCompositeOperation =
      //   "destination-out";
      // this.canvasProps.canvasObj.renderAll();
      // //打印图
      // console.log(
      //   "image data ",
      //   this.canvasProps.canvasObj.toDataURL({
      //     format: "png",
      //     multiplier: 1,
      //     quality: 1
      //   })
      // );
      // this.canvasProps.entityImage.visible = true;
      // this.canvasProps.overlayImage.globalCompositeOperation = "source-over";
      // this.canvasProps.canvasObj.renderAll();
    },
    onSaveJSON() {
      // alert(
      //   JSON.stringify(this.canvas.toJSON(["centeredRotation", "selectable"]))
      // );
      console.log(
        "data======",
        JSON.stringify(this.canvas.toJSON(["centeredRotation", "selectable"]))
      );
    },
    dataURLtoFile(imageData, filename) {
      //二进制转文件
      let arr = imageData.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    loadFabricImageAsync(imgUrl) {
      // 异步加载图片
      return new Promise(resolve => {
        fabric.Image.fromURL(
          imgUrl,
          fabricImage => {
            resolve(fabricImage);
          },
          { crossOrigin: "anonymous" }
        );
      });
    },
    async initCanvas() {
      const canvasFront = (this.canvasProps.canvasObj = new fabric.Canvas(
        "canvasFront",
        {
          backgroundColor: "transparent",
          width: 600,
          height: 600,
          // preserveObjectStacking: true,
          controlsAboveOverlay: true
          // perPixelTargetFind: true
        }
      ));
      if (this.sampleModel.id) {
        //已经保存过模板
        canvasFront.loadFromJSON(this.sampleModel.frontCanvasDataJson, () => {
          canvasFront.renderAll.bind(canvasFront);
          //初始化属性
          this.canvasProps.entityImage = canvasFront.getObjectByName(
            "entityImage"
          );
          this.canvasProps.overlayImage = this.canvasProps.canvasObj.overlayImage;
          console.log("重新复制canvas", this.canvasProps);
        });
        //
      }
      initAligningGuidelines(canvasFront);
      initCenteringGuidelines(canvasFront);
      //添加监听事件
      canvasFront.on({
        "selection:created": e => {
          console.log("selection:created", e.target.type);
          if (e.target.type === "text") {
            //选中了文字
            this.textProps.textBox = e.target;
            this.textProps.isNew = false;
            this.textProps.fontSize = e.target.fontSize;
            this.textProps.textColor = e.target.fill;
            this.textProps.fontWeight = e.target.fontWeight;
            this.textProps.fontFamily = e.target.fontFamily;
            this.textProps.textValue = e.target.text;
            this.textProps.shadow = e.target.shadow;
            this.textProps.stroke = e.target.stroke;
            this.textProps.strokeWidth = e.target.strokeWidth;
            this.textProps.textAlign = e.target.textAlign;
            this.textProps.lineHeight = e.target.lineHeight;
            this.textProps.textBackgroundColor = e.target.textBackgroundColor;
          } else {
            this.textProps = this.$options.data().textProps;
          }
        },
        "before:selection:cleared": e => {
          this.textProps = this.$options.data().textProps;
        }
      });
      //添加删除按钮
      this.addDeleteImgEventToFabric();
      // canvas.loadFromJSON(canvasJSONData, canvas.renderAll.bind(canvas));
      // canvas.setZoom(0.5)
      // canvas.zoomToPoint(new fabric.Point(300, 0), 0.5);
      // return;
      // 添加模具
      // const bottomImage = await this.loadFabricImageAsync(entityImg);
      // bottomImage.scaleToHeight(600 * 0.85);
      // bottomImage.selectable = false;
      // bottomImage.name = "bottomImage";
      // canvas.add(bottomImage);
      // canvas.centerObject(bottomImage);
      // canvas.renderAll();
      // this.bottomImage = bottomImage;
      // const backColorRect = new fabric.Rect({
      //   left: bottomImage.left,
      //   top: bottomImage.top,
      //   width: bottomImage.getScaledWidth(),
      //   height: bottomImage.getScaledHeight(),
      //   fill: "#ffffff",
      //   selectable: false,
      //   name: "backColorRect"
      // });
      // canvas.add(backColorRect);
      // canvas.sendToBack(backColorRect);
      // canvas.renderAll();
      // this.colorRect = backColorRect;
      //
      // const overlayImage = await this.loadFabricImageAsync(overlayImg);
      // canvas.setOverlayImage(overlayImage, canvas.renderAll.bind(canvas), {
      //   left: bottomImage.left,
      //   top: bottomImage.top,
      //   scaleX: bottomImage.scaleX,
      //   scaleY: bottomImage.scaleY
      // });
      // this.overlayImage = overlayImage;
      // const tiezhi = await this.loadFabricImageAsync(cutImg);
      // tiezhi.set({
      //   left: 200,
      //   top: 200,
      //   originX: "center",
      //   originY: "center",
      //   centeredScaling: true,
      //   centeredRotation: true
      // });
      // canvas.add(tiezhi);
      // const textBox = new fabric.Textbox("TEST FONT", {
      //   left: 250,
      //   top: 250,
      //   fontSize: 30,
      //   fontWeight: 600,
      //   hasControls: true,
      //   // hasBorders: true,
      //   // borderColor: '#000000',
      //   fill: "#000000",
      //   // perPixelTargetFind: true,
      //   // snapAngle: 90,
      //   editable: true,
      //   // angle: 90,
      //   // snapThreshold: 10,
      //   originX: "center",
      //   originY: "center"
      //   // editingBorderColor: "#ff8d23"
      // });
      // canvas.add(textBox);
      // let canvasData = canvas.toJSON(["centeredRotation", "selectable"]);
      // console.log("canvasData", JSON.stringify(canvas));
      // console.log("canvasData", JSON.stringify(canvasData));
    },
    deleteObject(eventData, target) {
      const canvas = target.canvas;
      canvas.remove(target);
      canvas.requestRenderAll();
    },
    addDeleteImgEventToFabric() {
      // 定制删除图片按钮
      console.log("定制删除图片按钮");
      fabric.Object.prototype.controls.deleteControl = new fabric.Control({
        x: 0.5,
        y: -0.5,
        offsetY: 16,
        cursorStyle: "pointer",
        mouseUpHandler: this.deleteObject,
        render: renderDeleteIcon,
        cornerSize: 24
      });
    },
    async loadStyleList() {
      return new Promise(resolve => {
        getSampleStyleByPage({
          size: 100,
          type: "DIY_TABLET_MUFF",
          orders: [{ column: "sort" }]
        }).then(data => {
          resolve(data.records);
        });
      });
    },
    loadTemplate() {
      return new Promise(resolve => {
        getTabletMuffTemplateById(this.tempId).then(data => {
          // this.sampleModel = data;
          resolve(data);
        });
      });
    }
  },
  async mounted() {
    //如果模板已存在，加载已存在的模板
    this.styleList = await this.loadStyleList();
    console.log("this.tempId", this.tempId);
    if (this.tempId) {
      //
      this.sampleModel = await this.loadTemplate();
    } else {
      console.log("this.styleList", this.styleList);
      this.sampleModel.styleId = this.styleList[0].id;
      this.sampleModel.skuId = this.skuId;
      this.sampleModel.skuName = this.skuName;
    }
    this.initCanvas();
  }
};
</script>

<style scoped>
.emt {
}
.canvas-area {
  margin-bottom: 15px;
  border-bottom: 1px solid #dcdfe6;
  padding: 15px;
}
.canvas-area >>> .canvas-container {
  min-width: 600px;
}
.canvas-area >>> .canvas-container {
  background-color: #eae8e040;
}
.emt >>> .el-form-item {
  margin-bottom: 10px;
}
</style>
